import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import notification from '@kuiper-components/notification';
import Button from '@kuiper-components/button';
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';
import recursion from '../../../../helpers/recursionForm';
import s from './style.module.css';
import Dialog from '@knownsec/react-component/dist/Dialog';
import Form from '@knownsec/react-component/dist/Form';
import Radio from '@knownsec/react-component/dist/Radio';
import Select from '@knownsec/react-component/dist/Select';
import moment from 'moment';
import fetchFer from 'API/fetch';
import Datetime from '@knownsec/react-component/dist/Datetime';
import { isIPv4, isIPv6 } from '../../../../../common/isIP';
export default function DateRangeSelect({ className, jobId, note, downBack }) {
	const defaultData = {
		job_ids: [],
		dateRange: [],
		download_type: 1,
	};
	const [dialogVisible, setDialogVisible] = React.useState(false);
	const [downloadable, setDownloadable] = React.useState(true);
	const [jobList, setJobList] = useState([]);
	const [form] = Form.useForm();
	const getAsset = async () => {
		const assetList = await fetchFer(`/api/v2/asset/verified-asset`, {
			method: 'GET',
		});
		const list = assetList.data.JobMany.map(item => {
			let sourceIp = '';
			if (isIPv4(item.sourceIp) || isIPv6(item.sourceIp)) {
				sourceIp = item.sourceIp;
			}
			return {
				label: `${item.note} ${item.targetUrl} ${sourceIp}`,
				labelHtml: `<span style="width: 100px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${
					item.note
				}'>${item.note}</span>
					 <span style="width: 200px;display: inline-block;margin-left: 10px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${
							item.targetUrl
						}'>${item.targetUrl}</span>
					${
						sourceIp
							? `<span style="width: 100px;display: inline-block;margin-left: 10px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${sourceIp}'>${sourceIp}</span>`
							: ''
					}
				 `,
				value: item.note + '\t' + item.id,
			};
		});
		setJobList(list);
	};
	const onValues = data => {
		const values = recursion(data);
		if (values.hasOwnProperty('dateRange')) {
			if (!values.dateRange) {
				values.dateRange = [];
			}
		}
		form.current.setFieldsValue(values);
	};
	const validatormap = (rule, value = {}) => {
		if (rule.field === 'job_ids') {
			if (!value[0]) {
				return Promise.reject('请选择资产');
			}
		}
		return Promise.resolve();
	};
	const submitForm = () => {
		form.current.validateFields().then(data => {
			if (!downloadable) return false;
			setDownloadable(false);
			const downloadName = [];
			const job_ids = [];
			data.job_ids.forEach(item => {
				const itemArr = item.split('\t');
				downloadName.push(itemArr[0]);
				job_ids.push(itemArr[1]);
			});
			const date =
				data.dateRange.length > 0
					? {
							start_date: moment(data.dateRange[0]).format(
								'YYYY-MM-DD HH:mm:ss'
							),
							end_date: moment(data.dateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
					  }
					: {};
			fetchFer(`/api/v2/report/download_task`, {
				method: 'POST',
				body: JSON.stringify({
					job_ids: job_ids.join(','),
					download_type: data.download_type.toString(),
					report_type: Object.keys(date).length > 0 ? 'range' : 'latest',
					...date,
				}),
			})
				.then(res => {
					if (res.code === 200) {
						form.current.setFieldsValue(defaultData);
						form.current.resetFields();
						downBack();
					} else {
						notification.error({
							message: `报告导出失败`,
							placement: 'top',
						});
					}
					setDownloadable(true);
					setDialogVisible(false);
				})
				.catch(e => {
					setDownloadable(true);
					setDialogVisible(false);
					notification.error({
						message: `报告导出失败`,
						placement: 'top',
					});
				});
		});
	};
	const disableDate = current => {
		return (
			current.diff(moment(), 'days', true) >= 0 ||
			current.diff(moment().subtract(180, 'days'), 'days', true) <= 0
		);
	};
	useEffect(() => {
		getAsset();
	}, []);
	useEffect(() => {
		if (dialogVisible && jobId) {
			form.current.setFieldsValue({
				job_ids: [`${note}\t${jobId}`],
			});
		}
	}, [dialogVisible]);
	return (
		<div className={s.container}>
			<Button
				className={cn(s.btn, className)}
				primary
				onClick={() => {
					form.current.setFieldsValue(defaultData);
					setDialogVisible(true);
					setDownloadable(true);
				}}
			>
				报告下载
			</Button>
			<Dialog
				className={s.w680}
				title="报告下载"
				visible={dialogVisible}
				onhide={() => {
					form.current.setFieldsValue(defaultData);
					form.current.resetFields();
					setDialogVisible(false);
				}}
				onsubmit={submitForm}
			>
				<div className={s.dcontent}>
					<div className={s.tip}>已下载的历史报告默认存储一周。</div>
					<Form
						ref={form}
						initialValues={defaultData}
						onValuesChange={(newItem, allValues) => {
							onValues(newItem, allValues);
						}}
						labelCol={{ span: 4 }}
						labelAlign="right"
						wrapperCol={{ span: 20 }}
					>
						<Form.Item
							label="资产"
							name="job_ids"
							rules={[{ required: true, validator: validatormap }]}
							className={s.jobIds}
						>
							<Select
								checkAll
								placeholder="请选择资产"
								multiple
								className={cn(s.w500, s.dSelect)}
								option={jobList}
								clearable
								searchable
							/>
						</Form.Item>
						<div className={s.pr}>
							<Form.Item label="时间范围" name="dateRange">
								<Datetime
									disabledDate={disableDate}
									onCalendarChange={date => {
										if (date?.length > 0) {
											form.current.setFieldsValue({ dateRange: date });
										} else {
											form.current.setFieldsValue({ dateRange: [] });
										}
									}}
									ranges={{
										今天: [moment().hours(0).minutes(0).seconds(0), moment()],
										昨天: [
											moment()
												.subtract(1, 'days')
												.hours(0)
												.minutes(0)
												.seconds(0),
											moment()
												.subtract(1, 'days')
												.hours(23)
												.minutes(59)
												.seconds(59),
										],
										最近7天: [
											moment()
												.subtract(6, 'days')
												.hours(0)
												.minutes(0)
												.seconds(0),
											moment(),
										],
									}}
									className={s.w500}
									dropdownClassName={s.z2002}
								/>
							</Form.Item>
							<span className={s.dateTip}>
								若不选时间范围，则默认下载最新一次监测结果
							</span>
						</div>
						<Form.Item label="导出方式" name="download_type">
							<Radio.Group>
								<Radio className={s.h22} value={1}>
									批量导出
								</Radio>
								<Radio className={cn(s.ml8, s.h22)} value={0}>
									合并导出
								</Radio>
							</Radio.Group>
						</Form.Item>
					</Form>
				</div>
			</Dialog>
		</div>
	);
}

DateRangeSelect.propTypes = {
	className: PropTypes.string,
};

DateRangeSelect.defaultProps = {
	className: s.dateRangeSelect,
};
